package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: tanhu1a
 * @description:
 * @author: MR.peng
 * @create: 2022-03-12 03:25
 **/

@DubboService
public class MovementApiImpl implements MovementApi {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;


    @Override
    public String save(Movement movement) {
        //1.保存动态详情到数据库中
        mongoTemplate.save(movement);
        //2.调用工具类方法，异步保存数据
        timeLineService.saveTimeLine(movement);
        return movement.getId().toString();
    }


    //.and("state").is(1)
    //api根据用户id，查询此用户发布的动态列表 List<Movement>
    @Override
    public List<Movement> findByUserId(Long userId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);//查询审核通过的动态
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pageSize)
                .limit(pageSize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    //根据好友id，查询此用户好友发布的动态列表
    @Override
    public List<Movement> findByFriendId(Long friendId, Integer page, Integer pageSize) {
        //根据friedId查询(动态-好友关系)
        Criteria linecriteria = Criteria.where("friendId").is(friendId);
        Query linequery = Query.query(linecriteria).with(Sort.by(Sort.Order.desc("created"))).
                skip((page - 1) * pageSize).limit(pageSize);

        List<MovementTimeLine> lines = mongoTemplate.find(linequery, MovementTimeLine.class);
        //提取所有动态id，
//        List<ObjectId> ids = new ArrayList<>();
//        for (MovementTimeLine line : lines) {
//            ids.add(line.getMovementId());
//        }
        List<ObjectId> ids = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);//从list集合中提取对象的某个属性
        //根据动态id查询所有动态
        Criteria criteria = Criteria.where("id").in(ids);
        Query query = Query.query(criteria);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    /*
     * 根据动态id列表，查询动态数据
     * */
    @Override
    public List<Movement> findByIds(String[] movementIds, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("id").in(movementIds).and("state").is(1);
        Query query = Query.query(criteria)
                .skip((page - 1) * pageSize)
                .limit(pageSize);
        return mongoTemplate.find(query,Movement.class);
    }

    /*
     * 随机查询动态数据
     * */
    @Override
    public List<Movement> randomMoveent(Integer count) {

        //设置采样数据
        //数量
        TypedAggregation<Movement> aggregation = TypedAggregation.newAggregation(Movement.class, Aggregation.sample(count));
        //查询
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //从采样结果中获取真实数据
        List<Movement> mappedResults = results.getMappedResults();
        return mappedResults;
    }

    /*
    * 根据id查询动态
    *
    * */
    @Override
    public Movement findById(String id) {
        Movement movement = mongoTemplate.findById(id, Movement.class);
        return movement;
    }


    //更新状态
    @Override
    public void updateState(String movementId, Integer state) {
        //1.构建Query
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        //构建update
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }

    //根据用户id和状态查询动态
    @Override
    public PageResult findMovements(Long uid, Integer status, Integer page, Integer pagesize) {
        //1.创建Query对象
        Query query = new Query();
        if(uid != null){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (status != null) {
            query.addCriteria(Criteria.where("state").is(status));
        }
        //2.查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //3.设置分页参数
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page-1) * pagesize).limit(pagesize);
        //4.查询列表
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }


    //查看动态详情 消息id
    @Override
    public Movement findDetails(String id) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(id));
        Query query = Query.query(criteria);
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        return movement;
    }

    // 动态通过 或 拒绝
    @Override
    public void updateStates(String[] ids, Integer state) {
        List<String> list = Arrays.asList(ids);
        Query query = Query.query(Criteria.where("id").in(list));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateMulti(query, update, Movement.class);
    }
}

